/**
 * 
 */
package fluo.centralserver;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author maherbeg
 *
 * Created: Apr 11, 2009
 * Modified: Apr 11, 2009
 */
public class RegistrationThread implements CentralServerDetails, Runnable {
	Socket client;
	
	CentralServer cs;

	public RegistrationThread(CentralServer cs, Socket s){
		client = s;
		this.cs = cs;
		Thread t = new Thread(this);
		t.start();
	}
	public void run() {
		ObjectOutputStream oos = null;
		ObjectInputStream ois = null;
		
		try {
			oos = new ObjectOutputStream(client.getOutputStream());
			ois = new ObjectInputStream(client.getInputStream());
			
			Object receiveData = ois.readObject();
			
			if(receiveData != null){
				if(receiveData instanceof RegisterDesktop){ //Lets register a desktop into our system
					RegisterDesktop desktop = (RegisterDesktop)receiveData;
					
					if(cs.registerDesktop(desktop))
						desktop.setAccepted(true);
					
					//Let the server know that we have accepted or denied them
					oos.writeObject(desktop);
				}
			} else{
				System.out.println("RegistrationThread.run()<" + client.getInetAddress() + ":" + client.getPort() +
									">: Received data was null, please send data again.");
			}
			
		} catch (IOException e) {
			System.out.println("RegistrationThread.run()<" + client.getInetAddress() + ":" + client.getPort() + 
								">: Error Creating Object Output/Input Stream, closing socket... ");
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.out.println("RegistrationThread.run()<" + client.getInetAddress() + ":" + client.getPort() +
								">: Error determining the type of object being sent, please send data again.");
			e.printStackTrace();
		}
		
		//Close our socket, we're finished
		try {
			client.close();
		} catch (IOException e1) {
			System.out.println("RegistrationThread.run()<" + client.getInetAddress() + ":" + client.getPort() +
								">: Error closing socket connection");
			e1.printStackTrace();
		}
	}
	
	
}
